﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


using Lb.BackDb;


using Lb.Common;
using LB.Common;

namespace Lb.BackDbFrm
{
    public partial class DbaseFrm : Form
    {
        public DbaseFrm()
        {
            this.InitializeComponent();
        }
        private SettingConfig _settingConfig = null;

        private string _currentDataBaseName = string.Empty;
        private string BackFaleName = string.Empty;

        /// <summary>
        /// 绑定消息
        /// </summary>
        /// <param name="text"></param>
        public delegate bool SetTextCallBack(string text);



        private void btnSetting_Click(object sender, EventArgs e)
        {
            new Settings().ShowDialog();

            this._settingConfig = XmlHelper.XmlDeserialize<SettingConfig>(SystemParam.ConfigFilePath);
            this.InitDbList();

        }



        private void DbaseFrm_Load(object sender, EventArgs e)
        {
            this.timer1.Start();
            //this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            if (!File.Exists(SystemParam.ConfigFilePath))
            {
                new Settings().ShowDialog();
            }
            this._settingConfig = XmlHelper.XmlDeserialize<SettingConfig>(SystemParam.ConfigFilePath);
            this.InitDbList();
        }

        private void InitDbList()
        {
            this.Invoke(new ClearDropDownItems(this.ClearDropDownData));

            foreach (string dbname in this._settingConfig.DataBaseNames)
            {
                this.Invoke(new CreateControlMenuItem(this.CreateMenuItemToDb), dbname);
            }
        }

        private void ClearDropDownData()
        {
            this.btnSelectDb.DropDownItems.Clear();
        }

        private void CreateMenuItemToDb(string dbname)
        {

            ToolStripMenuItem a = new ToolStripMenuItem
            {
                Name = dbname,
                Size = new System.Drawing.Size(152, 22),
                Text = dbname
            };
            a.Click += this.A_Click;
            if (this._currentDataBaseName == dbname)
            {
                a.Image = global::Lb.BackDbFrm.Properties.Resources.select2;
            }

            this.btnSelectDb.DropDownItems.Add(a);
        }
        private delegate void CreateControlMenuItem(string dbName);
        private delegate void ClearDropDownItems();



        private void A_Click(object sender, EventArgs e)
        {
            foreach (ToolStripMenuItem dropDownItem in this.btnSelectDb.DropDownItems)
            {
                dropDownItem.Image = null;
            }
            ToolStripMenuItem btn = sender as ToolStripMenuItem;
            btn.Image = null;//你的图标
            if (btn != null)
            {
                if (this._currentDataBaseName != btn.Name)
                {
                    btn.Image = global::Lb.BackDbFrm.Properties.Resources.select2;
                    this._currentDataBaseName = btn.Name;
                    this.gbDbName.Text = btn.Name + @" - 数据库备份列表(支持右键菜单)";
                    BindBackList();
                }
                else
                {
                    btn.Image = null;
                    this._currentDataBaseName = string.Empty;
                    this.gbDbName.Text = this._currentDataBaseName + @" - 数据库备份列表(支持右键菜单)";
                    BindBackList();
                }
            }
        }

        public bool SetFileName(string name)
        {
            bool isFilename = true;
            string[] errorStr = new string[] { "/", "\\", ":", ",", "*", "?", "\"", "<", ">", "|" };
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show(@"请输入文件名");
                return false;
            }
            else
            {
                foreach (string str in errorStr)
                {
                    if (name.Contains(str))
                    {
                        isFilename = false;
                        break;
                    }
                }
            }

            if (!isFilename)
            {
                MessageBox.Show(@"文件名不合法，请检查文件名中是否存在不合法字符");
                return false;
            }

            this.BackFaleName = name;
            return isFilename;
        }
        private void btnBak_Click(object sender, EventArgs e)
        {
            if (this._currentDataBaseName.IsNullOrEmptyEx())
            {
                MessageBox.Show(@"请选择要备份的数据库");
                return;
            }
            DBHelper.SetConnectionString(this._settingConfig.ServiceAddress, this._settingConfig.DataBaseLogin, this._settingConfig.DataBasePassword);
            SetMessageToDbFile f = new SetMessageToDbFile();
            f.BackDataBase = new SetTextCallBack(this.SetFileName);
            if (f.ShowDialog() == DialogResult.OK)
            {
                string saveFileName = DateTime.Now.ToString(this._settingConfig.NameRegulation)
                    .Replace("{DB}", this._currentDataBaseName).Replace("{备注}", BackFaleName);
                string saveFolder = this._settingConfig.BackDirectoryPath;
                if (this._settingConfig.IsNewFolder)
                {
                    saveFolder = Path.Combine(saveFolder, this._currentDataBaseName);
                    this.CheckDirectory(saveFolder);
                }

                saveFileName = Path.Combine(saveFolder, saveFileName);
                //开始备份数据库
                string sql = $"BACKUP DATABASE [{this._currentDataBaseName}] TO DISK = '{saveFileName}.bak' ";
                DBHelper.ExecuteSqlSetTimeOut(sql, 3600);
                BindBackList();
            }
        }
        /// <summary>
        /// 检查备份目录是否存在
        /// </summary>
        private void CheckDirectory(string dirName)
        {
            if (!Directory.Exists(dirName))
            {
                LogHelper.Log($"发现备份目录不存在，开始创建目录,目录:{dirName}");
                Directory.CreateDirectory(dirName);

            }
        }

        private void btnFoDbbak_Click(object sender, EventArgs e)
        {

        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void BindBackList()
        {

            dataGridView1.DataSource = new List<MyFileInfo>(); ;
            string dirname = Path.Combine(this._settingConfig.BackDirectoryPath, this._currentDataBaseName);
            if (Directory.Exists(dirname))
            {
                List<string> fileNameList = Directory.GetFiles(dirname, "*.bak").ToList();
                List<MyFileInfo> list = new List<MyFileInfo>();
                foreach (string file in fileNameList)
                {
                    list.Add(new MyFileInfo()
                    {
                        name = Path.GetFileName(file),
                        path = file
                    });
                }

                dataGridView1.DataSource = list;
            }
        }

        private void 复制文件名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.CopyText("文件名称");
        }

        private void CopyText(string cellname, string type = "default")
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                string value = this.dataGridView1.SelectedRows[0].Cells[cellname].Value.ToString();
                if (type == "dir")
                {
                    value = Path.GetDirectoryName(value);
                }
                Clipboard.SetDataObject(value);
                st_operMsg.Text = "复制完成 (3)";
            }
            else
            {
                MessageBox.Show("请选择要复制的行");
            }
        }

        private void 复制文件路径ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.CopyText("路径");

        }

        private void 复制目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.CopyText("路径", "dir");
        }

        private void 打开文件目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            string dirname = Path.Combine(this._settingConfig.BackDirectoryPath, this._currentDataBaseName);
            System.Diagnostics.Process.Start("Explorer.exe", dirname);
        }


        private void timer1_Tick(object sender, EventArgs e)
        {

            if (!this.st_operMsg.Text.IsNullOrEmptyEx())
            {
                var strs = this.st_operMsg.Text.Split(' ');
                int index = strs.Last().TrimStart('(').TrimEnd(')').ObjToInt();
                if (index == 0)
                {
                    this.st_operMsg.Text = string.Empty;
                }
                else
                {
                    this.st_operMsg.Text = strs[0] + $" ({--index})";
                }
            }

            this.st_Time.Text = "系统时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void 删除选中备份ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                int length = this.dataGridView1.SelectedRows.Count;
                for (int i = 0; i < length; i++)
                {
                    string value = this.dataGridView1.SelectedRows[i].Cells["路径"].Value.ToString();
                    File.Delete(value);
                }

                this.BindBackList();
                this.st_operMsg.Text = $"{length}个备份文件已删除！ (3)";
            }
            else
            {
                MessageBox.Show("请选择要删除的行");
            }

        }

        private void DbaseFrm_Resize(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                if (MessageBox.Show("正在最小化，是否隐藏到托盘？", "提醒", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
                    DialogResult.Yes)
                {
                    this.NotifyShow();
                }
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.Hide();//隐藏本窗体
            this.NotifyShow();
        }

        private void NotifyShow()
        {
            this.ShowInTaskbar = false;
            this.notifyIcon1.Visible = true; //展示出notifyicon控件
            this.notifyIcon1.ShowBalloonTip(20, "提示", " 数据库备份工具已经隐藏在此处", ToolTipIcon.Info);
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示    
                WindowState = FormWindowState.Normal;
            }
            else
            {
                this.Show();
            }
            //激活窗体并给予它焦点
            this.Activate();
            //任务栏区显示图标
            this.ShowInTaskbar = true;
            //托盘区图标隐藏
            notifyIcon1.Visible = false;
        }

        private void 显示窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示
                WindowState = FormWindowState.Normal;
            }
            else
            {
                this.Show();
            }
            //激活窗体并给予它焦点
            this.Activate();
            //任务栏区显示图标
            this.ShowInTaskbar = true;
            //托盘区图标隐藏
            notifyIcon1.Visible = false;
        }
    }

    class MyFileInfo
    {
        public string name { get; set; }
        public string path { get; set; }
    }

}
